package com.hluobo.gnnulibrary.engine;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import com.hluobo.gnnulibrary.model.UpdateInfo;

public class SplashService {

	private static final int TIMEOUTMILLIS = 1500;

	/**
	 * 获取服务器端更新数据
	 * @param serverPath 服务器端路径
	 * @return {@link UpdateInfo}
	 * @throws Exception
	 */
	public UpdateInfo getUpdateInfo(String serverPath) throws Exception {

		URL url = new URL(serverPath);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setConnectTimeout(TIMEOUTMILLIS);
		connection.setRequestMethod("GET");

		int responseCode = connection.getResponseCode();
		if (responseCode == HttpURLConnection.HTTP_OK) {
			InputStream is = connection.getInputStream();
			return parseFromInputStream(is);
		}

		return null;

	}

	/**
	 * 解析服务器端升级文件内容
	 * @param is 服务器端输入流
	 * @return  {@link UpdateInfo} 
	 */
	private UpdateInfo parseFromInputStream(InputStream is) {
		UpdateInfo info = new UpdateInfo();
		XmlPullParser parser = Xml.newPullParser();
		try {

			parser.setInput(is, "utf-8");

			int eventType = parser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {

				switch (eventType) {
				case XmlPullParser.START_TAG:
					if (parser.getName().equals("version")) {
						info.setVersion(Integer.parseInt(parser.nextText()));
					} else if (parser.getName().equals("description")) {
						info.setDescription(parser.nextText());
					} else if (parser.getName().equals("url")) {
						info.setUrl(parser.nextText());
					}
					break;
				}
				eventType = parser.next();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return info;
	}

}
